package ext.tianma.part.statute;

import java.io.Closeable;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.rmi.RemoteException;
import java.util.Locale;

import org.apache.log4j.Logger;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.apache.poi.xssf.usermodel.XSSFCell;

import ext.tianma.bom.util.StringUtil;
import ext.tianma.part.PartCommands;
import ext.tianma.part.forms.TMTypeUtil;
import ext.tianma.util.IbaAttributeUtil;
import ext.tianma.workflow.BomWorkFlowUtil;
import wt.doc.WTDocument;
import wt.fc.ObjectReference;
import wt.fc.PersistenceHelper;
import wt.fc.QueryResult;
import wt.fc.ReferenceFactory;
import wt.fc.WTObject;
import wt.log4j.LogR;
import wt.org.WTUser;
import wt.part.WTPart;
import wt.part.WTPartHelper;
import wt.project.Role;
import wt.query.QuerySpec;
import wt.query.SearchCondition;
import wt.team.Team;
import wt.team.TeamManaged;
import wt.type.ClientTypedUtility;
import wt.util.WTException;
import wt.util.WTPropertyVetoException;
import wt.workflow.engine.WfProcess;

/**
 * 用于物料根据物料的中英文名称,料号生效地添加环安审核者
 * 
 * @author laichao_sun
 *
 */
public class StatueSafeAssessor {
	private static final Logger log = LogR.getLogger(StatueSafeAssessor.class.getName());
	public static String STATUTE_PATH = "/ptc/Windchill/codebase/ext/tianma/part/config/status.xlsx";
	// 角色为环安审核
	private static String EnvSafe_value = "EnvSafeAssessor";

	public static boolean setSafeAssessor(WTObject object, ObjectReference self) {
		WTPart part = null;
		Workbook we = null;
		InputStream in = null;
		try {
			if (object instanceof WTPart) {
				part = (WTPart) object;
				if (TMTypeUtil.isRawMaterial(part)) {
					in = new FileInputStream(STATUTE_PATH);
					we = WorkbookFactory.create(in);
					if (null == STATUTE_PATH || STATUTE_PATH.equals("")) {
						throw new WTException("没有获取到环安审核者的配置路径，请检查!");
					}
					if (null == in || null == we) {
						throw new WTException("没有获取到环安审核者的配置路径，请检查!");
					}
					// 中英文名称
					String partCNAndENName = IbaAttributeUtil.getAttributeValue(part, "partCNAndENName");
					// 物料生效地
					String[] siteArray = ext.tianma.part.PartCommands.getEffectiveSiteOfPart(part);

					// 环保类别
					if (StringUtil.isNullOrEmpty(partCNAndENName)) {
						return false;
					}
					boolean bol = getSafeAssessor(object, self, we.getSheetAt(1), partCNAndENName, siteArray);

					return bol;
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			close(in);
		}

		return false;

	}

	private static boolean getSafeAssessor(WTObject object, ObjectReference self, Sheet sheet, String partCNAndENName,
			String[] siteArray) throws WTException {
		boolean flag = false;
		for (String site : siteArray) {

			for (int i = 1; i < sheet.getLastRowNum() + 1; i++) {
				Row row = sheet.getRow(i);
				if (row != null) {
					String temp = getCellValue(row.getCell(0)).trim();
					if (null == temp || temp.equals("")) {
						continue;
					} else {
						if (temp.contains(site)) {
							String temp1 = getCellValue(row.getCell(1)).trim();
							if (partCNAndENName.equals(temp1)) {
								String name = getCellValue(row.getCell(2)).trim();
								addPrincipalToRole(object, self, name);
								flag = true;
								break;
							}
						}
					}
				}
			}
		}
		return flag;

	}
	/**
	 * 判断进阶是否需要环安审核
	 * @param object
	 * @param self
	 * @return
	 */
	public static boolean isSafeAssessor(WTObject object, ObjectReference self) {
		WTPart part = null;
		Workbook we = null;
		InputStream in = null;
		try {
			if (object instanceof WTPart) {
				part = (WTPart) object;
				if (TMTypeUtil.isRawMaterial(part)) {
					in = new FileInputStream(STATUTE_PATH);
					we = WorkbookFactory.create(in);
					if (null == STATUTE_PATH || STATUTE_PATH.equals("")) {
						throw new WTException("没有获取到环安审核者的配置路径，请检查!");
					}
					if (null == in || null == we) {
						throw new WTException("没有获取到环安审核者的配置路径，请检查!");
					}
					// 中英文名称
					String partCNAndENName = IbaAttributeUtil.getAttributeValue(part, "partCNAndENName");
					// 物料生效地
					String[] siteArray = ext.tianma.part.PartCommands.getEffectiveSiteOfPart(part);

					// 环保类别
					if (StringUtil.isNullOrEmpty(partCNAndENName)) {
						return false;
					}
					boolean bol = isSafe(object, self, we.getSheetAt(1), partCNAndENName, siteArray);

					return bol;
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			close(in);
		}

		return false;

	}
	private static boolean isSafe(WTObject object, ObjectReference self, Sheet sheet, String partCNAndENName,
			String[] siteArray) throws WTException {
		boolean flag = false;
		for (String site : siteArray) {

			for (int i = 1; i < sheet.getLastRowNum() + 1; i++) {
				Row row = sheet.getRow(i);
				if (row != null) {
					String temp = getCellValue(row.getCell(0)).trim();
					if (null == temp || temp.equals("")) {
						continue;
					} else {
						if (temp.contains(site)) {
							String temp1 = getCellValue(row.getCell(1)).trim();
							if (partCNAndENName.equals(temp1)) {
								String name = getCellValue(row.getCell(2)).trim();
								flag = true;
								break;
							}
						}
					}
				}
			}
		}
		return flag;
	}
	/**
	 * 判断物料是否关联了说明方文档
	 * 
	 * @throws WTException *
	 * 
	 */
	public static void checkPartLink(WTObject primaryBusinessObject) throws WTException {
		try {
			if (primaryBusinessObject instanceof WTPart) {
				WTPart part = (WTPart) primaryBusinessObject;
				QueryResult qr = WTPartHelper.service.getDescribedByDocuments(part);
				WTPart part2 = PartCommands.getWTPartByNumber(part.getNumber());
				QueryResult qr2 = WTPartHelper.service.getDescribedByDocuments(part2);
				if (qr.size() == 0) {
					throw new WTException("注意上传环安资料，否则会被环安审核节点驳回，如有特殊沟通请附上沟通证据,如果忽略，请去除勾选后完成!");
				}
				boolean flag = true;
				while (qr.hasMoreElements()) {
					WTDocument doc = (WTDocument) qr.nextElement();
					String docType = ClientTypedUtility.getLocalizedTypeName(doc, Locale.CHINA);
					if ("环安审核资料".equals(docType)) {
						flag = false;
					}
				}
				if (flag) {
					throw new WTException("注意上传环安资料，否则会被环安审核节点驳回，如有特殊沟通请附上沟通证据,如果忽略，请去除勾选后完成!");
				}

			}
		} catch (RemoteException e) {
			e.printStackTrace();
		}

	}

	/**
	 * 给角色添加用户
	 * 
	 * @param self           obj
	 * @param internal_value 角色名
	 * @param name           用户名
	 * @throws WTPropertyVetoException
	 * @throws WTException
	 * @throws RemoteException
	 */
	public static void addPrincipalToRole(WTObject primaryBusinessObject, ObjectReference self, String name) {
		try {
			if (primaryBusinessObject instanceof WTPart) {
				WTPart part = (WTPart) primaryBusinessObject;
				String viewName = part.getViewName();
				log.info("viewName111====>>>" + viewName);

				WfProcess process = BomWorkFlowUtil.getProcess(self);
				wt.team.Team team = null;
				try {
					team = getTeam(process);
				} catch (Exception ex) {
					ex.printStackTrace();
					throw new WTException(ex);
				}

				Role theRole = Role.toRole(EnvSafe_value);
				WTUser user = getUserByName(name);
				log.info("theRole===" + theRole + "==>>user===>>" + user);
				if (user == null) {
					throw new WTException("没有找到用户: [" + user + "] ");
				} else {
					team.addPrincipal(theRole, user);
				}
				PersistenceHelper.manager.refresh(team);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	// 根据用户名查询WTUser对象
	public static WTUser getUserByName(String username) throws WTException {
		WTUser user = null;
		QuerySpec qs = new QuerySpec(WTUser.class);
		SearchCondition sc = new SearchCondition(WTUser.class, WTUser.NAME, "=", username);
		qs.appendWhere(sc);
		QueryResult qr = PersistenceHelper.manager.find(qs);
		while (qr.hasMoreElements()) {
			user = (WTUser) qr.nextElement();
		}
		return user;
	}

	/**
	 * 根据WfProcess对象，获得团队
	 * 
	 * @param process
	 * @return
	 * @throws Exception
	 */
	public static Team getTeam(WfProcess process) throws Exception {

		Team team = null;
		ReferenceFactory rf = new ReferenceFactory();
		String oid = rf.getReferenceString(process);
		WTObject wtobject = (WTObject) rf.getReference(oid).getObject();
		if (wtobject instanceof TeamManaged) {
			team = (Team) ((TeamManaged) wtobject).getTeamId().getObject();
		} else if (wtobject instanceof Team) {
			team = (Team) wtobject;
		}
		return team;
	}

	/**
	 * 获取单元格中的信息
	 * 
	 * @param cell 单元格
	 * @return 主要参数信息
	 * @throws Exception
	 */
	public static String getCellValue(Cell cell) throws WTException {
		String value = "";
		try {
			if (null == cell) {
				return "";
			}
			switch (cell.getCellType()) {
			case XSSFCell.CELL_TYPE_NUMERIC:
				value = Double.toString(cell.getNumericCellValue());
				break;
			case XSSFCell.CELL_TYPE_STRING:
				value = cell.getStringCellValue();
				break;
			case XSSFCell.CELL_TYPE_BLANK:
				value = "";
				break;
			case XSSFCell.CELL_TYPE_BOOLEAN:
				value = Boolean.toString(cell.getBooleanCellValue());
				break;
			case XSSFCell.CELL_TYPE_FORMULA:
				try {
					value = String.valueOf(cell.getNumericCellValue());
				} catch (Exception e) {
					value = cell.getStringCellValue();
				}
				break;
			default:
				break;
			}
		} catch (Exception e) {
		}

		return value.trim();
	}

	/**
	 * 关闭资源
	 * 
	 * @param closeable
	 */
	public static void close(Closeable closeable) {
		try {
			if (closeable != null) {
				closeable.close();
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
